package unicamp.redes.rmi;

import java.io.FileWriter;
import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * get the RMI Compute service and send a task to compute PI to N digits
 * 
 * @author srasul
 * 
 */
public class StartClient extends RmiStarter {

	public StartClient() throws IOException {
		super(Dac.class);
	}

	@Override
	public void doCustomRmiHandling() throws IOException {
		try {
			String fromServer;
			UserInput user = null;
			Registry registry = LocateRegistry.getRegistry();
			Dac dac = (Dac) registry.lookup(Dac.SERVICE_NAME);

			while (true) {
				Interface.printMenu();
				user = Interface.getUserInput();
				// XXX PARA TESTE
				for (int i = 0; i < 50; i++) {
//					Comentado para teste
//					if (user.getOption() == 0) {
//						return;
//					}
					user.setOption(1);
					long start = System.nanoTime();
					fromServer = dac.start(user.getOption(), user.getCode(),
							user.getUser(), user.getPass(),
							user.getCommentary());
					long end = System.nanoTime() - start;
					saveTimes(end);
					System.out.println(fromServer);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void saveTimes(long time) {
		FileWriter out;
		try {
			out = new FileWriter("times.txt", true);
			out.write(time + "\n");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			new StartClient();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
